package com.chen.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.annotation.OptLog;
import com.chen.common.OptTypeConst;
import com.chen.common.Result;
import com.chen.controller.dto.UploadDataListener;
import com.chen.entity.Question;
import com.chen.service.impl.QuestionServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 试卷管理
 *
 * @author personcoder007
 * @since 2022-08-16
 */
@RestController
@RequestMapping("/question")
@Api(value = "QuestionController", tags = "题库")
public class QuestionController {

    @Autowired
    private QuestionServiceImpl questionService;

    /**
     * 分页
     *
     * @param pageNum
     * @param pageSize
     * @param type
     * @return
     */
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询")
    public Result findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "5") Integer pageSize,
                           @RequestParam(defaultValue = "") Integer type,
                           @RequestParam(defaultValue = "") Integer courseId) {
        Page<Question> page = questionService.findPage(pageNum, pageSize, type, courseId);
        return Result.success(page);
    }

    /**
     * @param pageNum
     * @param pageSize
     * @param searchVal 根据试卷名称name 答案 answer 解析 detail
     * @return
     */
    @GetMapping("/getQuestionPage")
    @ApiOperation(value = "分页查询2")
    public Result getQuestionPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "5") Integer pageSize,
                                  @RequestParam(defaultValue = "") String searchVal,
                                  @RequestParam(defaultValue = "") String sortField) {

        HashMap map = new HashMap();
        if (!"".equals(searchVal)) {
            map.put("searchVal", searchVal);
        }
        if (!"".equals(sortField)) {
            map.put("sortField", sortField.toLowerCase());
        }
        Page<Question> page = questionService.getQuestionPage(pageNum, pageSize, map);
        return Result.success(page);
    }

    @PostMapping("/saveQuestion")
    @ApiOperation(value = "添加或者更新试卷")
    @OptLog(optType = OptTypeConst.UPDATE)
    public Result saveQuestion(@RequestBody Question question) {
        if (question.getId() == null) {
            // 获取当前用户id
            int userId = StpUtil.getLoginIdAsInt();
            question.setUserId(userId);
            question.setTime(new Date());
        }
        return Result.success(questionService.saveOrUpdate(question));
    }


    @GetMapping("/findById")
    @ApiOperation(value = "根据id进行查询")
    public Result findQuestionById(@RequestBody Long id) {
        return Result.success(questionService.getById(id));
    }


    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "删除")
    @OptLog(optType = OptTypeConst.REMOVE)
    public Result deleteById(@PathVariable("id") Long id) {

        return Result.success(questionService.removeById(id));
    }

    @PostMapping("/del/batch")
    @OptLog(optType = OptTypeConst.REMOVE_BATH)
    @ApiOperation(value = "批量删除")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        System.out.println(ids);
        questionService.delBath(ids);
        return Result.success();
    }

    @GetMapping("/findList")
    @ApiOperation(value = "查询所有题目")
    public Result findList() {
        return Result.success(questionService.list());
    }


    /**
     * 导出
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("export")
    @ApiOperation(value = "导出")
    public void download(HttpServletResponse response) throws IOException {
        List<Question> dataList = new ArrayList<>();

        List<Question> questionList = questionService.list();
        for (Question question : questionList) {
            Question question1 = new Question();
            question1.setId(question.getId());
            question1.setName(question.getName());
            question1.setType(question.getType());
            question1.setA(question.getA());
            question1.setB(question.getB());
            question1.setC(question.getC());
            question1.setD(question.getD());
            question1.setAnswer(question.getAnswer());
            question1.setTime(question.getTime());
            question1.setScore(question.getScore());
            question1.setDetail(question.getDetail());
            question1.setCourseId(question.getCourseId());
            question1.setUserId(question.getUserId());
            dataList.add(question1);
        }
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("题库", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Question.class).sheet("题库").doWrite(dataList);
    }


    /**
     * excel导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Question.class, new UploadDataListener(questionService)).sheet().doRead();
        return "success";
    }

    @GetMapping(value = "/downloadTemplate")
    public void downFrozenTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "question.xlsx";
        ServletOutputStream out;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("content-type:octet-stream");
        //文件在项目中的存放路径
        String filePath = getClass().getResource("/templates/question.xlsx").getPath();
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
        }
        filePath = URLDecoder.decode(filePath, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        FileInputStream inputStream = new FileInputStream(filePath);
        out = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = inputStream.read(buffer)) != -1) {
            //写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputStream.close();
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

